package com.zackeus.common.utils;

import java.security.SecureRandom;
import java.util.UUID;

/**
 * 唯一性ID算法的工具类
 * @name: IdGen
 * @author: zz
 * @date: 2022/9/19
 */
public class IdGen {

    private final SecureRandom random;
    private static volatile IdGen mInstance;

    private IdGen() {
        this.random = new SecureRandom();
    }

    public static IdGen getInstance() {
        if (mInstance == null) {
            synchronized (IdGen.class) {
                if (mInstance == null) {
                    mInstance = new IdGen();
                }
            }
        }
        return mInstance;
    }

    /**
     * 封装JDK自带的UUID, 通过Random数字生成, 中间无-分割
     * @return
     */
    public String uuid() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    /**
     * 使用SecureRandom随机生成Long
     * @return
     */
    public long randomLong() {
        return Math.abs(this.random.nextLong());
    }

    /**
     * 基于Base62编码的SecureRandom随机生成bytes
     * @param length
     * @return
     */
    public String randomBase62(int length) {
        byte[] randomBytes = new byte[length];
        this.random.nextBytes(randomBytes);
        return Codec.getInstance().encodeBase62(randomBytes);
    }
}
